'use strict';
import { useEffect, useState, useCallback } from "react";

function UseScrollPosition() {
  const [scrollPosition, setScrollPosition] = useState(0);

  // 使用 useCallback 缓存节流函数
  const handleScrollThrottled = useCallback(
    throttle(() => {
      const position = window.scrollY || window.pageYOffset;
      setScrollPosition(position);
    }, 100), // 每 100ms 执行一次
    []
  );

  useEffect(() => {
    window.addEventListener("scroll", handleScrollThrottled);
    return () => window.removeEventListener("scroll", handleScrollThrottled);
  }, [handleScrollThrottled]);

  return {
    scrollPosition
  };
}

// 简单的节流函数实现
function throttle(fn: Function, delay: number) {
  let lastCall = 0;
  return function (...args: any[]) {
    const now = new Date().getTime();
    if (now - lastCall < delay) return;
    lastCall = now;
    return fn(...args);
  };
}

export default UseScrollPosition;